<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单管理 - 哈尔滨双城区农产品物流园管理系统</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <div class="table-container">
        <div class="table-header">
            <h3 class="table-title">订单管理</h3>
            <div class="table-tools">
                <button id="addOrderBtn" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 创建订单
                </button>
                <div class="input-group ml-2" style="width: 300px;">
                    <input type="text" id="searchInput" class="form-control" placeholder="搜索订单号或客户名称">
                    <div class="input-group-append">
                        <button id="searchBtn" class="btn btn-outline-secondary">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="mb-3">
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-secondary filter-btn active" data-status="all">全部</button>
                <button type="button" class="btn btn-outline-primary filter-btn" data-status="pending">待处理</button>
                <button type="button" class="btn btn-outline-warning filter-btn" data-status="processing">处理中</button>
                <button type="button" class="btn btn-outline-success filter-btn" data-status="completed">已完成</button>
                <button type="button" class="btn btn-outline-danger filter-btn" data-status="cancelled">已取消</button>
            </div>
            
            <div class="btn-group ml-3" role="group">
                <button type="button" class="btn btn-outline-secondary date-filter-btn active" data-days="0">全部时间</button>
                <button type="button" class="btn btn-outline-secondary date-filter-btn" data-days="7">最近7天</button>
                <button type="button" class="btn btn-outline-secondary date-filter-btn" data-days="30">最近30天</button>
                <button type="button" class="btn btn-outline-secondary date-filter-btn" data-days="90">最近90天</button>
            </div>
        </div>
        
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th width="50px">
                        <input type="checkbox" id="checkAll">
                    </th>
                    <th>订单编号</th>
                    <th>客户名称</th>
                    <th>订单金额</th>
                    <th>支付状态</th>
                    <th>订单状态</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="orderTable">
                <!-- 数据将通过AJAX加载 -->
            </tbody>
        </table>
        
        <div class="row">
            <div class="col-md-6">
                <button id="batchDeleteBtn" class="btn btn-danger" disabled>
                    <i class="fas fa-trash"></i> 批量删除
                </button>
            </div>
            <div class="col-md-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-end" id="pagination">
                        <!-- 分页将通过JavaScript生成 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- 创建/编辑订单模态框 -->
    <div class="modal fade" id="orderModal" tabindex="-1" role="dialog" aria-labelledby="orderModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="orderModalLabel">创建订单</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="orderForm">
                        <input type="hidden" id="orderId">
                        
                        <div class="card mb-3">
                            <div class="card-header">
                                客户信息
                            </div>
                            <div class="card-body">
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label for="customerName">客户名称</label>
                                        <input type="text" class="form-control" id="customerName" required>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label for="contactPhone">联系电话</label>
                                        <input type="text" class="form-control" id="contactPhone" required>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="deliveryAddress">送货地址</label>
                                    <input type="text" class="form-control" id="deliveryAddress" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card mb-3">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <span>订单商品</span>
                                <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
                                    <i class="fas fa-plus"></i> 添加商品
                                </button>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="orderItemsTable">
                                        <thead>
                                            <tr>
                                                <th>产品名称</th>
                                                <th>单价(元)</th>
                                                <th>数量</th>
                                                <th>金额(元)</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="orderItems">
                                            <!-- 订单项将通过JavaScript动态添加 -->
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="3" class="text-right"><strong>总计：</strong></td>
                                                <td colspan="2"><span id="totalAmount">0.00</span> 元</td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-header">
                                订单信息
                            </div>
                            <div class="card-body">
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label for="orderStatus">订单状态</label>
                                        <select class="form-control" id="orderStatus" required>
                                            <option value="pending">待处理</option>
                                            <option value="processing">处理中</option>
                                            <option value="completed">已完成</option>
                                            <option value="cancelled">已取消</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label for="paymentStatus">支付状态</label>
                                        <select class="form-control" id="paymentStatus" required>
                                            <option value="unpaid">未支付</option>
                                            <option value="paid">已支付</option>
                                            <option value="refunded">已退款</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label for="paymentMethod">支付方式</label>
                                        <select class="form-control" id="paymentMethod">
                                            <option value="">请选择</option>
                                            <option value="cash">现金</option>
                                            <option value="bank_transfer">银行转账</option>
                                            <option value="credit_card">信用卡</option>
                                            <option value="wechat">微信支付</option>
                                            <option value="alipay">支付宝</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label for="expectedDeliveryDate">预计送货日期</label>
                                        <input type="date" class="form-control" id="expectedDeliveryDate">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="remark">备注</label>
                                    <textarea class="form-control" id="remark" rows="2"></textarea>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveOrderBtn">保存订单</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加订单项模态框 -->
    <div class="modal fade" id="addItemModal" tabindex="-1" role="dialog" aria-labelledby="addItemModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addItemModalLabel">添加商品</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="itemForm">
                        <div class="form-group">
                            <label for="productId">选择产品</label>
                            <select class="form-control" id="productId" required>
                                <option value="">请选择产品</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="unitPrice">单价(元)</label>
                            <input type="number" class="form-control" id="unitPrice" readonly>
                        </div>
                        <div class="form-group">
                            <label for="quantity">数量</label>
                            <input type="number" class="form-control" id="quantity" required min="1" value="1">
                        </div>
                        <div class="form-group">
                            <label for="itemAmount">金额(元)</label>
                            <input type="text" class="form-control" id="itemAmount" readonly>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="addItemToOrderBtn">添加</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 订单详情模态框 -->
    <div class="modal fade" id="orderDetailModal" tabindex="-1" role="dialog" aria-labelledby="orderDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="orderDetailModalLabel">订单详情</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card mb-3">
                                <div class="card-header">订单信息</div>
                                <div class="card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <th width="120px">订单编号</th>
                                            <td id="detail-orderId"></td>
                                        </tr>
                                        <tr>
                                            <th>创建时间</th>
                                            <td id="detail-createTime"></td>
                                        </tr>
                                        <tr>
                                            <th>订单状态</th>
                                            <td id="detail-orderStatus"></td>
                                        </tr>
                                        <tr>
                                            <th>支付状态</th>
                                            <td id="detail-paymentStatus"></td>
                                        </tr>
                                        <tr>
                                            <th>支付方式</th>
                                            <td id="detail-paymentMethod"></td>
                                        </tr>
                                        <tr>
                                            <th>送货日期</th>
                                            <td id="detail-deliveryDate"></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card mb-3">
                                <div class="card-header">客户信息</div>
                                <div class="card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <th width="120px">客户名称</th>
                                            <td id="detail-customerName"></td>
                                        </tr>
                                        <tr>
                                            <th>联系电话</th>
                                            <td id="detail-contactPhone"></td>
                                        </tr>
                                        <tr>
                                            <th>送货地址</th>
                                            <td id="detail-deliveryAddress"></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card mb-3">
                        <div class="card-header">订单商品</div>
                        <div class="card-body">
                            <table class="table table-bordered" id="detailItemsTable">
                                <thead>
                                    <tr>
                                        <th>产品名称</th>
                                        <th>单价(元)</th>
                                        <th>数量</th>
                                        <th>金额(元)</th>
                                    </tr>
                                </thead>
                                <tbody id="detailItems">
                                    <!-- 订单项将通过JavaScript动态添加 -->
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="3" class="text-right"><strong>总计：</strong></td>
                                        <td><span id="detail-totalAmount">0.00</span> 元</td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">备注</div>
                        <div class="card-body">
                            <p id="detail-remark">暂无备注</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-info" id="printOrderBtn">
                        <i class="fas fa-print"></i> 打印订单
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function() {
            let currentPage = 1;
            let pageSize = 10;
            let total = 0;
            let searchValue = '';
            let statusFilter = 'all';
            let dateFilter = 0;
            let orderItems = []; // 用于存储订单项
            
            // 加载订单数据
            function loadOrderData() {
                let requestData = {
                    pageNum: currentPage,
                    pageSize: pageSize
                };
                
                // 添加搜索条件
                if (searchValue) {
                    requestData.orderNo = searchValue;
                    requestData.customerName = searchValue;
                }
                
                // 添加状态过滤条件
                if (statusFilter !== 'all') {
                    requestData.orderStatus = statusFilter;
                }
                
                // 添加日期过滤条件
                if (dateFilter > 0) {
                    let today = new Date();
                    let startDate = new Date();
                    startDate.setDate(today.getDate() - dateFilter);
                    requestData.startDate = startDate.toISOString().split('T')[0];
                    requestData.endDate = today.toISOString().split('T')[0];
                }
                
                $.ajax({
                    url: '/finance/order/list',
                    type: 'GET',
                    data: requestData,
                    success: function(res) {
                        if (res.code === 200) {
                            renderOrderTable(res.data);
                            total = res.total;
                            renderPagination();
                        } else {
                            alert('加载数据失败：' + res.msg);
                        }
                    },
                    error: function() {
                        alert('加载数据失败，请检查网络连接');
                    }
                });
            }
            
            // 渲染订单表格
            function renderOrderTable(data) {
                let html = '';
                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        // 设置订单状态样式和文本
                        let statusClass = '';
                        let statusText = '';
                        
                        switch (item.orderStatus) {
                            case 'pending':
                                statusClass = 'badge badge-primary';
                                statusText = '待处理';
                                break;
                            case 'processing':
                                statusClass = 'badge badge-warning';
                                statusText = '处理中';
                                break;
                            case 'completed':
                                statusClass = 'badge badge-success';
                                statusText = '已完成';
                                break;
                            case 'cancelled':
                                statusClass = 'badge badge-danger';
                                statusText = '已取消';
                                break;
                            default:
                                statusClass = 'badge badge-secondary';
                                statusText = '未知';
                        }
                        
                        // 设置支付状态样式和文本
                        let paymentClass = '';
                        let paymentText = '';
                        
                        switch (item.paymentStatus) {
                            case 'unpaid':
                                paymentClass = 'badge badge-danger';
                                paymentText = '未支付';
                                break;
                            case 'paid':
                                paymentClass = 'badge badge-success';
                                paymentText = '已支付';
                                break;
                            case 'refunded':
                                paymentClass = 'badge badge-warning';
                                paymentText = '已退款';
                                break;
                            default:
                                paymentClass = 'badge badge-secondary';
                                paymentText = '未知';
                        }
                        
                        html += `<tr>
                            <td><input type="checkbox" class="order-checkbox" value="${item.orderId}"></td>
                            <td>${item.orderNo || ''}</td>
                            <td>${item.customerName}</td>
                            <td>¥${parseFloat(item.totalAmount).toFixed(2)}</td>
                            <td><span class="${paymentClass}">${paymentText}</span></td>
                            <td><span class="${statusClass}">${statusText}</span></td>
                            <td>${item.createTime}</td>
                            <td>
                                <button class="btn btn-sm btn-success view-btn" data-id="${item.orderId}" title="查看详情">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-info edit-btn" data-id="${item.orderId}" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${item.orderId}" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>`;
                    });
                } else {
                    html = '<tr><td colspan="8" class="text-center">暂无数据</td></tr>';
                }
                $('#orderTable').html(html);
                
                // 绑定按钮事件
                $('.view-btn').click(function() {
                    let orderId = $(this).data('id');
                    viewOrderDetail(orderId);
                });
                
                $('.edit-btn').click(function() {
                    let orderId = $(this).data('id');
                    editOrder(orderId);
                });
                
                $('.delete-btn').click(function() {
                    let orderId = $(this).data('id');
                    deleteOrder(orderId);
                });
                
                // 处理复选框状态
                handleCheckboxState();
            }
            
            // 渲染分页
            function renderPagination() {
                let totalPages = Math.ceil(total / pageSize);
                let html = '';
                
                // 上一页
                html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="javascript:void(0);" data-page="${currentPage - 1}">上一页</a>
                </li>`;
                
                // 页码
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, startPage + 4);
                
                for (let i = startPage; i <= endPage; i++) {
                    html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                        <a class="page-link" href="javascript:void(0);" data-page="${i}">${i}</a>
                    </li>`;
                }
                
                // 下一页
                html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="javascript:void(0);" data-page="${currentPage + 1}">下一页</a>
                </li>`;
                
                $('#pagination').html(html);
                
                // 绑定分页点击事件
                $('.page-link').click(function() {
                    if (!$(this).parent().hasClass('disabled')) {
                        currentPage = $(this).data('page');
                        loadOrderData();
                    }
                });
            }
            
            // 处理复选框状态
            function handleCheckboxState() {
                // 全选/取消全选
                $('#checkAll').change(function() {
                    $('.order-checkbox').prop('checked', $(this).prop('checked'));
                    updateBatchDeleteButton();
                });
                
                // 单个复选框变化
                $('.order-checkbox').change(function() {
                    updateBatchDeleteButton();
                    
                    // 更新全选框状态
                    let allChecked = $('.order-checkbox:checked').length === $('.order-checkbox').length;
                    $('#checkAll').prop('checked', allChecked);
                });
                
                updateBatchDeleteButton();
            }
            
            // 更新批量删除按钮状态
            function updateBatchDeleteButton() {
                let checkedCount = $('.order-checkbox:checked').length;
                $('#batchDeleteBtn').prop('disabled', checkedCount === 0);
            }
            
            // 加载产品下拉列表
            function loadProductOptions() {
                $.ajax({
                    url: '/product/list',
                    type: 'GET',
                    data: {
                        pageSize: 100,  // 获取更多产品用于下拉选择
                        pageNum: 1
                    },
                    success: function(res) {
                        if (res.code === 200) {
                            let html = '<option value="">请选择产品</option>';
                            res.data.forEach(function(item) {
                                html += `<option value="${item.productId}" data-price="${item.price}" data-name="${item.productName}">
                                    ${item.productName} (${item.specification})
                                </option>`;
                            });
                            $('#productId').html(html);
                        } else {
                            alert('加载产品数据失败：' + res.msg);
                        }
                    },
                    error: function() {
                        alert('加载产品数据失败，请检查网络连接');
                    }
                });
            }
            
            // 查看订单详情
            function viewOrderDetail(orderId) {
                $.ajax({
                    url: '/finance/order/getInfo',
                    type: 'GET',
                    data: {
                        orderId: orderId
                    },
                    success: function(res) {
                        if (res.code === 200) {
                            let data = res.data;
                            
                            // 填充订单信息
                            $('#detail-orderId').text(data.orderNo || data.orderId);
                            $('#detail-createTime').text(data.createTime);
                            
                            // 设置订单状态文本
                            let orderStatusText = '';
                            switch (data.orderStatus) {
                                case 'pending':
                                    orderStatusText = '<span class="badge badge-primary">待处理</span>';
                                    break;
                                case 'processing':
                                    orderStatusText = '<span class="badge badge-warning">处理中</span>';
                                    break;
                                case 'completed':
                                    orderStatusText = '<span class="badge badge-success">已完成</span>';
                                    break;
                                case 'cancelled':
                                    orderStatusText = '<span class="badge badge-danger">已取消</span>';
                                    break;
                                default:
                                    orderStatusText = '<span class="badge badge-secondary">未知</span>';
                            }
                            $('#detail-orderStatus').html(orderStatusText);
                            
                            // 设置支付状态文本
                            let paymentStatusText = '';
                            switch (data.paymentStatus) {
                                case 'unpaid':
                                    paymentStatusText = '<span class="badge badge-danger">未支付</span>';
                                    break;
                                case 'paid':
                                    paymentStatusText = '<span class="badge badge-success">已支付</span>';
                                    break;
                                case 'refunded':
                                    paymentStatusText = '<span class="badge badge-warning">已退款</span>';
                                    break;
                                default:
                                    paymentStatusText = '<span class="badge badge-secondary">未知</span>';
                            }
                            $('#detail-paymentStatus').html(paymentStatusText);
                            
                            // 设置支付方式文本
                            let paymentMethodText = '';
                            switch (data.paymentMethod) {
                                case 'cash':
                                    paymentMethodText = '现金';
                                    break;
                                case 'bank_transfer':
                                    paymentMethodText = '银行转账';
                                    break;
                                case 'credit_card':
                                    paymentMethodText = '信用卡';
                                    break;
                                case 'wechat':
                                    paymentMethodText = '微信支付';
                                    break;
                                case 'alipay':
                                    paymentMethodText = '支付宝';
                                    break;
                                default:
                                    paymentMethodText = '未指定';
                            }
                            $('#detail-paymentMethod').text(paymentMethodText);
                            
                            $('#detail-deliveryDate').text(data.expectedDeliveryDate || '未指定');
                            
                            // 填充客户信息
                            $('#detail-customerName').text(data.customerName);
                            $('#detail-contactPhone').text(data.contactPhone);
                            $('#detail-deliveryAddress').text(data.deliveryAddress);
                            
                            // 填充订单项
                            let itemsHtml = '';
                            let totalAmount = 0;
                            
                            if (data.orderItems && data.orderItems.length > 0) {
                                data.orderItems.forEach(function(item) {
                                    let amount = item.quantity * item.unitPrice;
                                    totalAmount += amount;
                                    
                                    itemsHtml += `<tr>
                                        <td>${item.productName}</td>
                                        <td>¥${parseFloat(item.unitPrice).toFixed(2)}</td>
                                        <td>${item.quantity}</td>
                                        <td>¥${parseFloat(amount).toFixed(2)}</td>
                                    </tr>`;
                                });
                            } else {
                                itemsHtml = '<tr><td colspan="4" class="text-center">暂无订单项</td></tr>';
                            }
                            
                            $('#detailItems').html(itemsHtml);
                            $('#detail-totalAmount').text(parseFloat(totalAmount).toFixed(2));
                            
                            // 填充备注
                            $('#detail-remark').text(data.remark || '暂无备注');
                            
                            // 显示模态框
                            $('#orderDetailModal').modal('show');
                        } else {
                            alert('获取订单详情失败：' + res.msg);
                        }
                    },
                    error: function() {
                        alert('获取订单详情失败，请检查网络连接');
                    }
                });
            }
            
            // 创建新订单
            $('#addOrderBtn').click(function() {
                // 重置表单和订单项
                $('#orderForm')[0].reset();
                $('#orderId').val('');
                orderItems = [];
                renderOrderItems();
                
                // 设置默认日期（今天之后7天）
                let defaultDate = new Date();
                defaultDate.setDate(defaultDate.getDate() + 7);
                $('#expectedDeliveryDate').val(defaultDate.toISOString().split('T')[0]);
                
                // 显示模态框
                $('#orderModalLabel').text('创建订单');
                $('#orderModal').modal('show');
            });
            
            // 编辑订单
            function editOrder(orderId) {
                $.ajax({
                    url: '/finance/order/getInfo',
                    type: 'GET',
                    data: {
                        orderId: orderId
                    },
                    success: function(res) {
                        if (res.code === 200) {
                            let data = res.data;
                            
                            // 填充表单
                            $('#orderId').val(data.orderId);
                            $('#customerName').val(data.customerName);
                            $('#contactPhone').val(data.contactPhone);
                            $('#deliveryAddress').val(data.deliveryAddress);
                            $('#orderStatus').val(data.orderStatus);
                            $('#paymentStatus').val(data.paymentStatus);
                            $('#paymentMethod').val(data.paymentMethod);
                            $('#expectedDeliveryDate').val(data.expectedDeliveryDate);
                            $('#remark').val(data.remark);
                            
                            // 填充订单项
                            orderItems = data.orderItems || [];
                            renderOrderItems();
                            
                            // 显示模态框
                            $('#orderModalLabel').text('编辑订单');
                            $('#orderModal').modal('show');
                        } else {
                            alert('获取订单详情失败：' + res.msg);
                        }
                    },
                    error: function() {
                        alert('获取订单详情失败，请检查网络连接');
                    }
                });
            }
            
            // 添加订单项按钮点击事件
            $('#addItemBtn').click(function() {
                // 加载产品选项
                loadProductOptions();
                
                // 重置表单
                $('#itemForm')[0].reset();
                
                // 显示模态框
                $('#addItemModal').modal('show');
            });
            
            // 产品选择变化时更新单价
            $('#productId').change(function() {
                let selectedOption = $(this).find('option:selected');
                let price = selectedOption.data('price') || 0;
                $('#unitPrice').val(price);
                updateItemAmount();
            });
            
            // 数量变化时更新金额
            $('#quantity').on('input', function() {
                updateItemAmount();
            });
            
            // 更新订单项金额
            function updateItemAmount() {
                let unitPrice = parseFloat($('#unitPrice').val()) || 0;
                let quantity = parseInt($('#quantity').val()) || 0;
                let amount = unitPrice * quantity;
                $('#itemAmount').val(amount.toFixed(2));
            }
            
            // 添加订单项到订单
            $('#addItemToOrderBtn').click(function() {
                // 表单验证
                if (!$('#itemForm')[0].checkValidity()) {
                    $('#itemForm')[0].reportValidity();
                    return;
                }
                
                let productId = $('#productId').val();
                let productName = $('#productId option:selected').data('name');
                let unitPrice = parseFloat($('#unitPrice').val());
                let quantity = parseInt($('#quantity').val());
                let amount = unitPrice * quantity;
                
                // 添加到订单项数组
                orderItems.push({
                    productId: productId,
                    productName: productName,
                    unitPrice: unitPrice,
                    quantity: quantity,
                    amount: amount
                });
                
                // 渲染订单项
                renderOrderItems();
                
                // 关闭模态框
                $('#addItemModal').modal('hide');
            });
            
            // 渲染订单项
            function renderOrderItems() {
                let html = '';
                let totalAmount = 0;
                
                if (orderItems.length > 0) {
                    orderItems.forEach(function(item, index) {
                        totalAmount += item.amount;
                        
                        html += `<tr>
                            <td>${item.productName}</td>
                            <td>¥${parseFloat(item.unitPrice).toFixed(2)}</td>
                            <td>${item.quantity}</td>
                            <td>¥${parseFloat(item.amount).toFixed(2)}</td>
                            <td>
                                <button type="button" class="btn btn-sm btn-danger remove-item-btn" data-index="${index}">
                                    <i class="fas fa-times"></i>
                                </button>
                            </td>
                        </tr>`;
                    });
                } else {
                    html = '<tr><td colspan="5" class="text-center">暂无订单项，请添加商品</td></tr>';
                }
                
                $('#orderItems').html(html);
                $('#totalAmount').text(parseFloat(totalAmount).toFixed(2));
                
                // 绑定移除按钮事件
                $('.remove-item-btn').click(function() {
                    let index = $(this).data('index');
                    orderItems.splice(index, 1);
                    renderOrderItems();
                });
            }
            
            // 保存订单
            $('#saveOrderBtn').click(function() {
                // 表单验证
                if (!$('#orderForm')[0].checkValidity()) {
                    $('#orderForm')[0].reportValidity();
                    return;
                }
                
                // 验证是否有订单项
                if (orderItems.length === 0) {
                    alert('请至少添加一个商品到订单中');
                    return;
                }
                
                // 收集表单数据
                let orderId = $('#orderId').val();
                let isAdd = !orderId;
                
                let totalAmount = 0;
                orderItems.forEach(function(item) {
                    totalAmount += item.amount;
                });
                
                let data = {
                    customerName: $('#customerName').val(),
                    contactPhone: $('#contactPhone').val(),
                    deliveryAddress: $('#deliveryAddress').val(),
                    orderStatus: $('#orderStatus').val(),
                    paymentStatus: $('#paymentStatus').val(),
                    paymentMethod: $('#paymentMethod').val(),
                    expectedDeliveryDate: $('#expectedDeliveryDate').val(),
                    remark: $('#remark').val(),
                    totalAmount: totalAmount,
                    orderItems: orderItems
                };
                
                // 如果是编辑，添加ID
                if (!isAdd) {
                    data.orderId = orderId;
                }
                
                // 发送请求
                $.ajax({
                    url: isAdd ? '/finance/order/add' : '/finance/order/edit',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function(res) {
                        if (res.code === 200) {
                            alert(isAdd ? '创建订单成功' : '更新订单成功');
                            $('#orderModal').modal('hide');
                            loadOrderData();
                        } else {
                            alert((isAdd ? '创建' : '更新') + '订单失败：' + res.msg);
                        }
                    },
                    error: function() {
                        alert((isAdd ? '创建' : '更新') + '订单失败，请检查网络连接');
                    }
                });
            });
            
            // 删除订单
            function deleteOrder(orderId) {
                if (confirm('确定要删除该订单吗？')) {
                    $.ajax({
                        url: '/finance/order/remove',
                        type: 'POST',
                        data: {
                            orderIds: orderId
                        },
                        success: function(res) {
                            if (res.code === 200) {
                                alert('删除成功');
                                loadOrderData();
                            } else {
                                alert('删除失败：' + res.msg);
                            }
                        },
                        error: function() {
                            alert('删除失败，请检查网络连接');
                        }
                    });
                }
            }
            
            // 批量删除
            $('#batchDeleteBtn').click(function() {
                let selectedIds = [];
                $('.order-checkbox:checked').each(function() {
                    selectedIds.push($(this).val());
                });
                
                if (selectedIds.length > 0 && confirm('确定要删除选中的 ' + selectedIds.length + ' 个订单吗？')) {
                    $.ajax({
                        url: '/finance/order/remove',
                        type: 'POST',
                        data: {
                            orderIds: selectedIds.join(',')
                        },
                        success: function(res) {
                            if (res.code === 200) {
                                alert('批量删除成功');
                                $('#checkAll').prop('checked', false);
                                loadOrderData();
                            } else {
                                alert('批量删除失败：' + res.msg);
                            }
                        },
                        error: function() {
                            alert('批量删除失败，请检查网络连接');
                        }
                    });
                }
            });
            
            // 搜索
            $('#searchBtn').click(function() {
                searchValue = $('#searchInput').val();
                currentPage = 1;
                loadOrderData();
            });
            
            // 回车搜索
            $('#searchInput').keypress(function(e) {
                if (e.which === 13) {
                    $('#searchBtn').click();
                    return false;
                }
            });
            
            // 状态过滤
            $('.filter-btn').click(function() {
                $('.filter-btn').removeClass('active');
                $(this).addClass('active');
                statusFilter = $(this).data('status');
                currentPage = 1;
                loadOrderData();
            });
            
            // 日期过滤
            $('.date-filter-btn').click(function() {
                $('.date-filter-btn').removeClass('active');
                $(this).addClass('active');
                dateFilter = $(this).data('days');
                currentPage = 1;
                loadOrderData();
            });
            
            // 打印订单
            $('#printOrderBtn').click(function() {
                let printContents = document.getElementById('orderDetailModal').innerHTML;
                let originalContents = document.body.innerHTML;
                
                document.body.innerHTML = `
                    <div style="padding: 20px;">
                        <h2 style="text-align: center;">订单详情</h2>
                        ${printContents}
                    </div>
                `;
                
                window.print();
                document.body.innerHTML = originalContents;
                
                // 重新绑定事件
                $(document).ready(function() {
                    loadOrderData();
                    
                    // 绑定其他事件...
                });
            });
            
            // 初始加载数据
            loadOrderData();
        });
    </script>
</body>
</html> 